package servlet;

import com.alibaba.fastjson.JSON;
import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        UserService userService = new UserServiceImpl();
        User user = new User();
        Map map = new HashMap();
        String mapJson = "";

        String uno = req.getParameter("uno");
        String pwd = req.getParameter("pwd");
        ResultSet rs = userService.selectUser(uno,pwd);

        try {
            if (rs.next()){
                int uid = rs.getInt("uid");
                uno = rs.getString("uno");
                String uname = rs.getString("uname");
                pwd = rs.getString("pwd");
                String sex = rs.getString("sex");
                String photo = rs.getString("photo");

                user.setUid(uid);
                user.setUno(uno);
                user.setUname(uname);
                user.setPwd(pwd);
                user.setSex(sex);
                user.setPhoto(photo);

                map.put("code","200");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("user",user);

        mapJson = JSON.toJSONString(map);
        out.print(mapJson);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
